package com.sinping.qh.api.admin.noticebook;


import com.sinping.qh.api.app.base.BaseAppEndPoint;
import com.sinping.qh.api.support.*;
import com.sinping.qh.dto.admin.noticebook.NoticeBookAuditDto;
import com.sinping.qh.dto.admin.noticebook.NoticeBookReturnDto;
import com.sinping.qh.dto.admin.record.HiddendangerRecordDto;
import com.sinping.qh.dto.common.CommonDTO;
import com.sinping.qh.service.MongoManager;
import com.sinping.qh.service.admin.noticebook.INoticeBookService;
import com.sinping.qh.utils.mapper.JsonMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.*;

/**
 * @author jiahuaiqing
 * @create 2018/5/29
 */
@Api(value = "admin通知书管理", description = "admin通知书管理")
@RestController
@RequestMapping(name = "admin通知书管理", value = Const.ADMIN_URI + "notice_book")
@Slf4j
public class NoticeBookEndPoint extends BaseAppEndPoint {

    //private final static Logger log = LoggerFactory.getLogger(NoticeBookEndPoint.class);

    @Autowired
    private Validator globalValidator;

    @Autowired
    MongoManager mongoManager;

    @Autowired
    INoticeBookService iNoticeBookService;

    @ApiOperation(httpMethod = "POST", value = "生成通知书记录", consumes = MediaTypes.JSON,notes = "都是必填字段")
    @RequestMapping(method = RequestMethod.POST, name = "生成通知书记录")
    public ResDto addNoticeBook(HttpServletRequest request,@ApiParam(name = "msg", value = "{\"notice_receive_unit_id\":\"xxxxxx\",<Br>\"notice_receive_unit_name\":\"xxxxxx\",\"notice_send_depart\":\"xxxxxx\",<Br>\"notice_leader\":\"xxxx\",\"notice_check_desc\":\"xxxx\",<Br>\"notice_check_requirement\":\"xxxx\",<br>\"hidden_danger_ids\":[\"id\",\"id\"]}")
                                @RequestParam(required = true) String msg) {

        try {
            NoticeBookReturnDto noticeBookDto = JsonMapper.defaultMapper().fromJson(msg, NoticeBookReturnDto.class);
            if (noticeBookDto == null) {
                log.error("参数为空或有不正确的数据格式");
                return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
            }
            //校验数据
            Set<ConstraintViolation<NoticeBookReturnDto>> validateSet = globalValidator.validate(noticeBookDto);
            if (!validateSet.isEmpty()) {
                StringBuffer buffer = new StringBuffer(64);
                for (ConstraintViolation<NoticeBookReturnDto> apiViolation : validateSet) {
                    buffer.append(apiViolation.getMessage());
                }
                log.info("必传参数 :{}", buffer.toString());
                ResDto resDto = new ResDto();
                resDto.setStatus(Const.PARAM_ERROR);
                resDto.setMsg(buffer.toString());
                return resDto;
            }

            ResDto resDto = iNoticeBookService.addNoticeBook(request,noticeBookDto);
            return resDto;
        } catch (Exception e) {
            log.error("数据解析异常{}", e);
            ResDto resDto = new ResDto();
            resDto.setStatus(Const.FORMAT_ERROR);
            resDto.setMsg("数据解析异常");
            return resDto;
        }
    }

    @ApiOperation(httpMethod = "GET", value = "通知书列表", consumes = MediaTypes.JSON,notes = "notice_status由string改成[],如\"3\"改为[\"3\"]")
    @RequestMapping(value = "/list", name = "通知书列表", method = RequestMethod.GET)
    public ResDto getNoticeBookFrontPage(@ApiParam(name = "msg", value = "{\"page_size\":10, \"page_current\":1, \"order_column\":null, \"order_by\":null, " +
            "\"condition\":{\"notice_receive_unit_id\":\"\",\"notice_send_date_start\":\"\",\"notice_send_date_end\":\"\"}}")
                                         @RequestParam(required = true) String msg) {
        try {
            log.info("入参 {}", msg);
            //1.String msg=> FrontPage page
            FrontPage page = JsonMapper.defaultMapper().fromJson(msg, FrontPage.class);
            if (page == null) {
                log.error("参数为空或有不正确的数据格式");
                return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
            }
            CommonDTO commonDTO =new CommonDTO();
            commonDTO.setToken(getToken());
            ResDto resDto = iNoticeBookService.noticeBookFrontPage(page,commonDTO);
            return resDto;
        } catch (Exception e) {
            log.error("数据解析异常{}", e);
            ResDto resDto = new ResDto();
            resDto.setStatus(Const.FORMAT_ERROR);
            resDto.setMsg("数据解析异常");
            return resDto;
        }

    }


    @ApiOperation(httpMethod = "PUT", value = "修改通知书信息",consumes = MediaTypes.JSON)
    @RequestMapping(name = "修改通知书信息", method = RequestMethod.PUT)
    public ResDto updateNoticeBook(HttpServletRequest request,@ApiParam(name = "msg", value = "{\"id\":\"xxxxxx\",\"notice_send_depart\":\"xxxxxx\",\"notice_leader\":\"xxxx\",\"notice_check_desc\":\"xxxx\",\"notice_check_requirement\":\"xxxx\",<br>\"hidden_danger_ids\":[\"id\",\"id\"]}")
                                   @RequestParam(required = true) String msg) {
        try {
            NoticeBookReturnDto noticeBookDto = JsonMapper.defaultMapper().fromJson(msg, NoticeBookReturnDto.class);
            if (noticeBookDto == null) {
                log.error("参数为空或有不正确的数据格式");
                return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
            }
            Set<ConstraintViolation<NoticeBookReturnDto>> validateSet = globalValidator.validate(noticeBookDto);
            if (!validateSet.isEmpty()) {
                StringBuffer buffer = new StringBuffer(64);
                for (ConstraintViolation<NoticeBookReturnDto> apiNoticeBookDta : validateSet) {
                    buffer.append(apiNoticeBookDta.getMessage());
                }
                log.info("", buffer.toString());
                ResDto resDto = new ResDto();
                resDto.setStatus(Const.PARAM_ERROR);
                resDto.setMsg(buffer.toString());
                return resDto;
            }

            ResDto resDto = iNoticeBookService.updateNoticeBook(request,noticeBookDto);
            return resDto;
        } catch (Exception e) {
            ResDto resDto = new ResDto(ConstEum.PARAM_ERROR);
            resDto.setStatus(Const.FORMAT_ERROR);
            resDto.setMsg("数据解析异常");
            return resDto;
        }

    }


    /**
     * 获取通知书详情(基本信息/隐患信息/通知书审核信息)
     *
     * @param id
     * @return
     */
    @ApiOperation(httpMethod = "GET", value = "获取通知书详情", consumes = MediaTypes.JSON)
    @RequestMapping(value = "/{id}", name = "通知书详情", method = RequestMethod.GET)
    public ResDto getNoticeBookById(@ApiParam(name = "id", value = "id:5b0e7a300a4145204c48768c") @PathVariable String id) {
        if (!StringUtils.isNotBlank(id)) {
            log.info("必传参数 :{}", "id");
            return new ResDto(Const.PARAM_ERROR, "id");
        }
        ResDto resDto = iNoticeBookService.getNoticeBookById(id);
        return resDto;
    }


    /**
     * 通知书的审核、整改方案的审核
     *
     * @param msg
     * @return
     */
    @ApiOperation(httpMethod = "POST", value = "添加通知书审核信息", consumes = MediaTypes.JSON)
    @RequestMapping(value = "/audit", name = "添加通知书审核信息", method = RequestMethod.POST)
    public ResDto addNoticeBookAudit(HttpServletRequest request,@ApiParam(name = "msg", value = "{\"notice_no\":\"xxxxxx\",\"notice_audit_result\":\"xxxx\",\"notice_audit_advice\":\"xxxx\",<br>\"notice_audit_source\":\"xxxx\"}")
                                     @RequestParam(required = true) String msg) {
        NoticeBookAuditDto noticeBookAuditDto = JsonMapper.defaultMapper().fromJson(msg, NoticeBookAuditDto.class);
        if (noticeBookAuditDto == null) {
            log.error("参数为空或有不正确的数据格式");
            return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
        }
        if (!StringUtils.isNotBlank(noticeBookAuditDto.getNoticeNo())) {
            return new ResDto(Const.FORMAT_ERROR, "通知书编号不为空");
        }
        if (!StringUtils.isNotBlank(noticeBookAuditDto.getNoticeAuditResult())) {
            return new ResDto(Const.FORMAT_ERROR, "审核结果不为空");
        }

        if (!StringUtils.isNotBlank(noticeBookAuditDto.getNoticeAuditSource())) {
            return new ResDto(Const.FORMAT_ERROR, "审核来源不为空");
        }

        ResDto resDto = iNoticeBookService.addNoticeBookAudit(request,noticeBookAuditDto);
        return resDto;
    }


    /**
     * 修改通知书状态或通知书方案状态
     *
     * @param msg
     * @return
     */
    @ApiOperation(httpMethod = "PUT", value = "修改通知书状态或通知书方案状态", consumes = MediaTypes.JSON)
    @RequestMapping(value = "/audit", name = "修改通知书状态或通知书方案状态", method = RequestMethod.PUT)
    public ResDto updateNoticeBookStatus(HttpServletRequest request,@ApiParam(name = "msg", value = "{\"notice_no\":\"xxxxxx\",\"notice_case_status\":\"xxxx\",\"notice_status\":\"xxxx\"}")
                                         @RequestParam(required = true) String msg) {

        try {
            NoticeBookReturnDto noticeBookDto = JsonMapper.defaultMapper().fromJson(msg, NoticeBookReturnDto.class);
            if (noticeBookDto == null) {
                log.error("参数为空或有不正确的数据格式");
                return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
            }
            if (!StringUtils.isNotBlank(noticeBookDto.getNoticeNo())) {
                return new ResDto(Const.FORMAT_ERROR, "通知书编号不为空");
            }
            ResDto resDto = iNoticeBookService.updateNoticeBookStatus(request,noticeBookDto);
            return resDto;
        } catch (Exception e) {
            log.error("数据解析异常");
            return new ResDto(Const.FORMAT_ERROR, "数据解析异常");
        }

    }

    /**
     * 添加通知书整改方案 (操作：添加到这个表中--隐患记录(tb_hidden_danger))
     *
     * @param msg id ---隐患记录的id
     * @return
     */
    @ApiOperation(httpMethod = "POST", value = "添加通知书整改方案", consumes = MediaTypes.JSON)
    @RequestMapping(value = "/case", name = "添加通知书整改方案", method = RequestMethod.POST)
    public ResDto addNoticeBookCaseInfo(HttpServletRequest request,@ApiParam(name = "msg", value = "[{\"notice_no\":\"xxxxxx\",\"id\":\"xxxxxx\",\"desc\":\"xxxx\",\"pre_time\":\"xxxx\"}]")
                                        @RequestParam(required = true) String msg) {
        try {
            List<HiddendangerRecordDto> hiddendangerRecordDtoList = JsonMapper.defaultMapper().fromJson(msg,
                    JsonMapper.defaultMapper().buildCollectionType(java.util.List.class, HiddendangerRecordDto.class));
            if (null == hiddendangerRecordDtoList || hiddendangerRecordDtoList.isEmpty()) {
                log.info("必传参数 :{}", "提交数据不能为空");
                return new ResDto(Const.PARAM_ERROR, "提交数据不能为空");
            }

            for (HiddendangerRecordDto hiddendangerRecordDto : hiddendangerRecordDtoList) {
                if (!StringUtils.isNotBlank(hiddendangerRecordDto.getId())) {
                    log.info("必传参数 :{}", "隐患id不能为空");
                    return new ResDto(Const.PARAM_ERROR, "隐患id不能为空");
                }
                if (!StringUtils.isNotBlank(hiddendangerRecordDto.getNoticeNo())) {
                    log.info("必传参数 :{}", "通知书编号不能为空");
                    return new ResDto(Const.PARAM_ERROR, "通知书编号不能为空");
                }
                Date preTime = hiddendangerRecordDto.getPreTime();
                if (null == preTime) {
                    log.info("必传参数 :{}", "预计完成时间不能为空");
                    return new ResDto(Const.PARAM_ERROR, "预计完成时间不能为空");
                }
            }

            ResDto resDto = iNoticeBookService.addNoticeBookCaseInfo(request,hiddendangerRecordDtoList);
            return resDto;
        } catch (Exception e) {
            log.error("数据解析异常");
            return new ResDto(Const.FORMAT_ERROR, "数据解析异常");
        }
    }


    /**
     * 修改通知书整改方案(操作：添加到这个表中--隐患记录(tb_hidden_danger))
     *
     * @param msg
     * @return
     */
    @ApiOperation(httpMethod = "PUT", value = "修改通知书整改方案", consumes = MediaTypes.JSON)
    @RequestMapping(value = "/case", name = "修改通知书整改方案", method = RequestMethod.PUT)
    public ResDto updateNoticeBookCaseInfo(HttpServletRequest request,@ApiParam(name = "msg", value = "[{\"notice_no\":\"xxxxxx\",\"id\":\"xxxxxx\",\"case_method\":\"xxxx\",\"pre_time\":\"xxxx\"}]")
                                           @RequestParam(required = true) String msg) {

        try{
            List<HiddendangerRecordDto> hiddendangerRecordDtoList = JsonMapper.defaultMapper().fromJson(msg, JsonMapper.defaultMapper().buildCollectionType(List.class, HiddendangerRecordDto.class));
            if (null == hiddendangerRecordDtoList || hiddendangerRecordDtoList.isEmpty()) {
                log.info("必传参数 :{}", "提交数据不能为空");
                return new ResDto(Const.PARAM_ERROR, "提交数据不能为空");
            }
            for (HiddendangerRecordDto hiddendangerRecordDto : hiddendangerRecordDtoList) {
                if (!StringUtils.isNotBlank(hiddendangerRecordDto.getNoticeNo())) {
                    log.info("必传参数 :{}", "通知书编号不能为空");
                    return new ResDto(Const.PARAM_ERROR, "通知书编号不能为空");
                }
                if (!StringUtils.isNotBlank(hiddendangerRecordDto.getId())) {
                    log.info("必传参数 :{}", "隐患id不能为空");
                    return new ResDto(Const.PARAM_ERROR, "隐患id不能为空");
                }
                Date preTime = hiddendangerRecordDto.getPreTime();
                if (null == preTime) {
                    log.info("必传参数 :{}", "预计完成时间不能为空");
                    return new ResDto(Const.PARAM_ERROR, "预计完成时间不能为空");
                }
            }

            ResDto resDto = iNoticeBookService.updateNoticeBookCaseInfo(request,hiddendangerRecordDtoList);
            return resDto;
        }catch (Exception e){
            log.error("数据解析异常");
            return new ResDto(Const.FORMAT_ERROR, "数据解析异常");
        }

    }


    /**
     * 获取通知书整改方案(操作：添加到这个表中--隐患记录(tb_hidden_danger))
     * 获取通知书整改方案详情(基本信息/隐患信息/通知书整改方案审核信息)
     * @param id
     * @return
     */
    @ApiOperation(httpMethod = "GET", value = "获取通知书整改方案", consumes = MediaTypes.JSON)
    @RequestMapping(value = "/case/{id}", name = "获取通知书整改方案", method = RequestMethod.GET)
    public ResDto getNoticeBookCaseInfo(@ApiParam(name = "id", value = "id:5b0e7a300a4145204c48768c") @PathVariable String id) {
        if (!StringUtils.isNotBlank(id)) {
            log.info("必传参数 :{}", "id");
            return new ResDto(Const.PARAM_ERROR, "id");
        }
        ResDto resDto = iNoticeBookService.getNoticeBookCaseInfo(id);
        return resDto;
    }

    /**
     * 生成整改报告(先查通知书的详情再生成word报告)
     */
    @ApiOperation(httpMethod = "GET", value = "生成整改报告word", consumes = MediaTypes.JSON,notes = "id:通知书id")
    @RequestMapping(value = "/generatereport/{id}", name = "生成整改报告word", method = RequestMethod.GET)
    public ResDto generateReportWord(@ApiParam(name = "id", value = "5b0e7a300a4145204c48768c") @PathVariable String id) {
        if (!StringUtils.isNotBlank(id)) {
            log.info("必传参数 :{}", "id");
            return new ResDto(Const.PARAM_ERROR, "id");
        }
        ResDto resDto = iNoticeBookService.generateReportNoticeBookById(id);
        return resDto;
    }

}
